package org.excample.controller;


import jakarta.validation.constraints.Pattern;
import org.hibernate.validator.constraints.URL;
import org.excample.entity.Result;
import org.excample.entity.User;
import org.excample.service.UserService;
import org.excample.utils.JwtUtil;
import org.excample.utils.Md5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController//控制层
@RequestMapping("/user")
@Validated//支持参数验证注解
public class UserController {

    //注册
    @Autowired
    private UserService userService;
    @PostMapping("register")
    public Result register(@Pattern(regexp="^\\S{5,16}$")String username, @Pattern(regexp="^\\S{5,16}$")String password){
        User u = userService.findUserByName(username);
        if(u != null){
            return Result.error("用户名已存在");
        }else {
            userService.register(username, password);
            return Result.success();
        }
    }

    //登录
    @PostMapping("login")
    public Result login(@Pattern(regexp="^\\S{5,16}$")String username, @Pattern(regexp="^\\S{5,16}$")String password){
        User user = userService.findUserByName(username);
        if(user == null){
            return Result.error("用户不存在");
        }
        if(Md5Util.getMD5String(password).equals(user.getPassword())){
            //登录成功生成令牌
            Map<String,Object> claims = new HashMap<>();
            claims.put("username",username);
            claims.put("id",user.getId());
            String token = JwtUtil.genToken(claims);
            return Result.success(token);
        }
        return Result.error("密码错误");
    }

    //获取用户详细信息
    @GetMapping("userinfo")
    public Result userInfo(@RequestHeader(name="Authorization") String token){
        //根据用户名查询用户信息
        //token中已经保存用户名了，可以从token中直接获取用户名
        Map<String,Object> map = JwtUtil.parseToken(token);
        String username = (String) map.get("username");
        User user = userService.findUserByName(username);
        return Result.success(user);
    }

    //更新用户信息
    @PutMapping("/update")
    public Result update(@RequestBody @Validated User user){
        userService.updateUser(user);
        return Result.success();
    }

    //更新头像
    @PatchMapping("updateAvatar")
    public Result updateAvatar(@RequestParam @URL String avatarUrl){
        userService.updateAvatar(avatarUrl);
        return Result.success();
    }

    //修改密码


}
